package com.cz.zslu.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cz.zslu.common.DigestUtils;
import com.cz.zslu.common.ReturnObject;
import com.cz.zslu.entity.*;
import com.cz.zslu.interceptor.BaseContextHandler;
import com.cz.zslu.interceptor.IgnoreAuth;
import com.cz.zslu.service.*;
import com.cz.zslu.utils.Sms;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 权限控制层
 *
 * @author sensen
 **/
@RestController
@RequestMapping("/web/auth")
@Api(description = "登录注册")
public class AuthApi {
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private IZslCodeService iZslCodeService;
    @Autowired
    private IBaseAreaService iBaseAreaService;
    @Autowired
    private IZslStoreService iZslStoreService;
    @Autowired
    private LoginStatisticsService loginStatisticsService;
    @Autowired
    private CommondityStatisticsService commondityStatisticsService;
    @Autowired
    private IZslAuthenticationService iZslAuthenticationService;


    @ApiOperation("获取一级")
    @IgnoreAuth
    @RequestMapping(value = "/getAreaList", method = RequestMethod.POST)
    public ReturnObject<List<BaseArea>> getAreaList() {
        EntityWrapper<BaseArea> ew = new EntityWrapper<>();
        ew.eq("type", 1);
        ew.orderBy("crt_time", true);
        return new ReturnObject<>(0, "获取成功", iBaseAreaService.selectList(ew));
    }


    @ApiOperation("获取二级或三级")
    @IgnoreAuth
    @RequestMapping(value = "/getListByPid", method = RequestMethod.POST)
    public ReturnObject<List<BaseArea>> getListByPid(@ApiParam("上级id") @RequestParam Long id) {
        EntityWrapper<BaseArea> ew = new EntityWrapper<>();
        ew.eq("pid", id);
        ew.orderBy("crt_time", false);
        return new ReturnObject<>(0, "获取成功", iBaseAreaService.selectList(ew));
    }

    @ApiOperation("01注册获取验证")
    @IgnoreAuth
    @RequestMapping(value = "/getcode", method = RequestMethod.POST)
    public ReturnObject<String> getcode(@ApiParam("手机号") @RequestParam String phone, @ApiParam("验证码类型（0:注册短信，1" +
            "：修改密码短信）") @RequestParam Long type) {

        try {
            if (type == 0) {
                List<SysUser> list = iSysUserService.selectList(new EntityWrapper<SysUser>().eq("phone", phone));
                if (list.size() > 0) {
                    return new ReturnObject(1, "手机号已注册，请更换手机号", "");
                }
            }
            ZslCode info = new ZslCode();
            info.setPhone(phone);
            info.setCode(Integer.toString((int) ((Math.random() * 9 + 1) * 100000)));
            Map<String, Object> map = Maps.newHashMap();
            map.put("code", info.getCode());
            if (type == 0) {
                Sms.sendSms(phone, "SMS_150470317", JSONObject.toJSONString(map));
            } else {
                Sms.sendSms(phone, "SMS_150470316", JSONObject.toJSONString(map));
            }
            iZslCodeService.insert(info);
            return new ReturnObject(0, "验证码已发送", info.getCode());
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了", "");
        }
    }


    @ApiOperation("02注册验证验证码")
    @IgnoreAuth
    @RequestMapping(value = "/verification", method = RequestMethod.POST)
    public ReturnObject<Object> verification(@ApiParam("手机号") @RequestParam String phone,
                                             @ApiParam("验证码") @RequestParam String code) {

        try {
            List<ZslCode> list = iZslCodeService.selectList(new EntityWrapper<ZslCode>().eq("phone", phone).eq("code"
                    , code));
            if (list.size() > 0) {
                return new ReturnObject(0, "验证成功", "");
            }
            return new ReturnObject(1, "验证码不正确", "");
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了", "");
        }
    }

    @ApiOperation("03注册信息提交")
    @IgnoreAuth
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ReturnObject<Object> register(@ApiParam("用户名") @RequestParam String username,
                                         @ApiParam("手机号") @RequestParam String phone,
                                         @ApiParam("密码") @RequestParam String password) {

        try {
            if (iSysUserService.selectCount(new EntityWrapper<SysUser>().eq("phone", phone)) > 0) {
                return new ReturnObject(1, "手机号已注册，请更换手机号", "");
            }
            if (iSysUserService.selectCount(new EntityWrapper<SysUser>().eq("username", username)) > 0) {
                return new ReturnObject(1, "用户名已存在，请更换用户名", "");
            }
            //新增店铺信息
            ZslStore store = new ZslStore();
            store.setName(username);
            store.setPhone(phone);
            iZslStoreService.insert(store);
            SysUser sysUser = new SysUser();
            sysUser.setStatus(0);
            sysUser.setNickName("zsl" + sysUser.getPhone());
            sysUser.setPhone(phone);
            sysUser.setUsername(username);
            sysUser.setType(1);
            sysUser.setFlat(4);
            sysUser.setStoreName(username);
            sysUser.setStoreId(store.getId());
            sysUser.setPassword(DigestUtils.md5Hex(password));
            sysUser.setToken(UUID.randomUUID().toString().replace("-", ""));
            sysUser.setCanCarry(new BigDecimal(0));
            sysUser.setHaveWithdrawal(new BigDecimal(0));
            sysUser.setWithdrawalOf(new BigDecimal(0));
            sysUser.setMarketingNum(0);
            iSysUserService.insert(sysUser);
            //新用户注册时，对认证信息进行新增，公司名称同店铺名称
            ZslAuthentication zslAuthentication = new ZslAuthentication();
            zslAuthentication.setCompanyName(username);
            zslAuthentication.setPhone(phone);
            zslAuthentication.setUserId(sysUser.getId());
            zslAuthentication.setState(6);
            iZslAuthenticationService.insert(zslAuthentication);
            LoginStatistics loginStatistics = new LoginStatistics();
            loginStatistics.setUserId(sysUser.getId());
            loginStatistics.setCrtTime(new Date());
            loginStatistics.setState(0);
            loginStatisticsService.insert(loginStatistics);

            return new ReturnObject(0, "注册成功", "");
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了", "");
        }
    }

    @ApiOperation("修改密码/忘记密码")
    @IgnoreAuth
    @RequestMapping(value = "/resetpassword", method = RequestMethod.POST)
    public ReturnObject<Object> resetpassword(@ApiParam("手机号") @RequestParam String phone,
                                              @ApiParam("验证码") @RequestParam String code,
                                              @ApiParam("新密码") @RequestParam String newpassword) {

        try {
            List<ZslCode> list = iZslCodeService.selectList(new EntityWrapper<ZslCode>().eq("phone", phone).eq("code"
                    , code));
            if (list.size() > 0) {
                List<SysUser> sysUsers = iSysUserService.selectList(new EntityWrapper<SysUser>().eq("phone", phone));
                if (sysUsers.size() > 0) {
                    SysUser sysUser = sysUsers.get(0);
                    sysUser.setPassword(DigestUtils.md5Hex(newpassword));
                    iSysUserService.updateById(sysUser);

                    return new ReturnObject(0, "修改成功", "");
                }

                return new ReturnObject(1, "当前手机号未注册", "");
            }
            return new ReturnObject(1, "验证码不正确", "");
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了", "");
        }
    }

    @ApiOperation("商场后台修改密码")
    @RequestMapping(value = "/updatepassword", method = RequestMethod.POST)
    public ReturnObject<Object> updatepassword(@ApiParam("原密码") @RequestParam String oldPassword,
                                               @ApiParam("新密码") @RequestParam String newpassword,
                                               @ApiParam("确认密码") @RequestParam String confirmpassword) {

        try {
            SysUser sysUser = iSysUserService.selectById(BaseContextHandler.getUserID());
            if (sysUser != null) {
                oldPassword = DigestUtils.md5Hex(oldPassword);
                if (oldPassword.equals(sysUser.getPassword())) {
                    if (newpassword.equals(confirmpassword)) {
                        sysUser.setPassword(DigestUtils.md5Hex(newpassword));
                        iSysUserService.updateById(sysUser);
                        return new ReturnObject(0, "密码修改成功！");

                    } else {
                        return new ReturnObject(1, "输入的密码不一致，请核对后再输入！");
                    }

                } else {
                    return new ReturnObject(1, "输入的旧密码不正确！");
                }

            } else {

                return new ReturnObject(1, "请重新登录！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了", "");
        }
    }


    @ApiOperation("管理后台重置密码")
    @RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
    public ReturnObject<Object> resetPassword(@ApiParam("新密码") @RequestParam String newpassword,
                                              @ApiParam("userId") @RequestParam Long userId) {

        try {
            if (userId != null) {
                SysUser sysUser = iSysUserService.selectById(userId);
                if (sysUser != null) {
                    sysUser.setPassword(DigestUtils.md5Hex(newpassword));
                    iSysUserService.updateById(sysUser);
                    return new ReturnObject(0, "密码重置成功！");
                } else {

                    return new ReturnObject(1, "请重新登录！");
                }

            }
            return new ReturnObject(1, "请重新登录！");

        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了", "");
        }
    }


    @ApiOperation("统一登录")
    @IgnoreAuth
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ReturnObject<Object> login(@ApiParam("用户名") @RequestParam String username,
                                      @ApiParam("密码") @RequestParam String password) {

        try {
            List<SysUser> list =
                    iSysUserService.selectList(new EntityWrapper<SysUser>().eq("username", username).or().eq("phone",
                            username));
            if (list != null && list.size() >= 1) {
                if (list.size() > 1) {
                    return new ReturnObject(1, "存在多重用户，请联系管理员");
                } else {
                    SysUser sysUser = list.get(0);
                    if (sysUser.getStatus() == 0) {
                        password = DigestUtils.md5Hex(password);
                        if (password.equals(sysUser.getPassword())) {
                            List<LoginStatistics> list1 = loginStatisticsService.selectList(new EntityWrapper<LoginStatistics>().eq("user_id", sysUser.getId()).orderBy("crt_time", false));
                            Date lastLoginTime = null;
                            if (list1 != null && list1.size() > 0) {
                                lastLoginTime = list1.get(0).getCrtTime();
                            }
                            LoginStatistics newloginStatistics = new LoginStatistics();
                            newloginStatistics.setUserId(sysUser.getId());
                            loginStatisticsService.insert(newloginStatistics);

                            CommondityStatistics commondityStatistics = commondityStatisticsService.selectOne(new EntityWrapper<CommondityStatistics>().eq("user_id", sysUser.getId()));
                            if (commondityStatistics != null) {
                                commondityStatistics.setLoginNumber(commondityStatistics.getLoginNumber() + 1);
                                commondityStatistics.setLoginTime(lastLoginTime);
                                commondityStatisticsService.updateById(commondityStatistics);
                            } else {
                                CommondityStatistics newCommondityStatistics = new CommondityStatistics();
                                newCommondityStatistics.setLoginNumber((long) 1);
                                newCommondityStatistics.setUserId(sysUser.getId());
                                newCommondityStatistics.setStoreId(sysUser.getStoreId());
                                newCommondityStatistics.setLoginTime(new Date());
                                commondityStatisticsService.insert(newCommondityStatistics);
                            }
                            return new ReturnObject(0, "登录成功", sysUser.getToken());
                        }
                        return new ReturnObject(1, "密码错误", "");
                    } else {
                        return new ReturnObject(1, "对不起，您的账号已经被禁用，请联系管理员！", "");
                    }
                }
            } else {
                return new ReturnObject(1, "用户名不存在，请联系管理员");
            }


        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了", "");
        }
    }

    @ApiOperation("统一获取个人信息")
    @RequestMapping(value = "/info", method = RequestMethod.POST)
    public ReturnObject<SysUser> info() {
        try {
            SysUser userVo = iSysUserService.selectById(BaseContextHandler.getUserID());

            if (userVo == null) {
                return new ReturnObject(401, "当前登录身份已失效，请重新登录", "");
            }

            return new ReturnObject(0, "请求成功", userVo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了", "");
        }
    }

    @ApiOperation("统一修改头像")
    @RequestMapping(value = "/updataInfo", method = RequestMethod.POST)
    public ReturnObject<Object> updataInfo(@ApiParam("头像地址") String picUrl) {
        try {
            SysUser sysUser = iSysUserService.selectById(BaseContextHandler.getUserID());
            if (sysUser == null) {
                return new ReturnObject(401, "请重新登录", "");
            }
            if (picUrl != null && !picUrl.isEmpty()) {
                sysUser.setPicUrl(picUrl);
            }
            iSysUserService.updateById(sysUser);
            return new ReturnObject(0, "更新成功", "");
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了", "");
        }
    }

    public static void main(String[] args) {
        System.out.println(DigestUtils.md5Hex("admin"));
        System.out.println(UUID.randomUUID().toString().replace("-", ""));
    }


}
